import 'dart:developer';
import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:get/get.dart';
import 'package:image_picker/image_picker.dart';
import 'package:short_drama/utils/colors.dart';

import '../../utils/http_util.dart';
import '../../utils/validate.dart';
import 'package:short_drama/utils/float.dart';

class RealNameAuthentication extends StatefulWidget {
  const RealNameAuthentication({super.key});

  @override
  State<RealNameAuthentication> createState() => _RealNameAuthenticationState();
}

// real_name_authentication_bg
class _RealNameAuthenticationState extends State<RealNameAuthentication> {
  File? _imageTop;
  File? _image;

  String? topImgUrl;
  String? bottomImgUrl;
  String? name;
  String? cardNum;

  Future<void> _takePhoto(type) async {
    final picker = ImagePicker();
    final pickedFile = await picker.pickImage(source: ImageSource.gallery);

    if (pickedFile != null) {
      setState(() {
        if (type == 0) {
          _imageTop = File(pickedFile.path);
          if (_imageTop != null) {
            _uploadFile(_imageTop!, true);
          }
        } else {
          _image = File(pickedFile.path);
          if (_image != null) {
            _uploadFile(_image!, false);
          }
        }
      });
    } else {
      log('用户取消拍照');
    }
  }

  Future<void> _uploadFile(File file, bool isTop) async {
    EasyLoading.show(status: 'loading', maskType: EasyLoadingMaskType.clear);
    try {
      final result = await HttpUtil().upload(
        'file/image',
        filePath: file.path,
        file: file,
        fileName: "身份证图片",
      );
      final dynamic responseData = result.data['data'];
      if (isTop) {
        topImgUrl = responseData['url'];
      } else {
        bottomImgUrl = responseData['url'];
      }
    } catch (e) {
      EasyLoading.showToast('请求失败');
    }
    EasyLoading.dismiss();
  }

  Future<void> submitInfo(
    String reaName,
    String codeNumber,
    String cardFront,
    String cardBack,
  ) async {
    EasyLoading.show(status: 'loading', maskType: EasyLoadingMaskType.clear);
    try {
      final result = await HttpUtil().post(
        'member/real_info',
        params: {
          "real_name": reaName,
          "code_number": codeNumber,
          "card_front": cardFront,
          "card_back": cardBack,
        },
      );
      final dynamic responseData = result.data['data']; // 明确类型
      EasyLoading.showToast('上传成功');
      Get.back();
    } catch (e) {
      EasyLoading.showToast('请求失败');
    }
    EasyLoading.dismiss();
  }

  _doneAction() {
    if (topImgUrl == null) {
      EasyLoading.showToast('请上传身份证正面');
      return;
    }
    if (bottomImgUrl == null) {
      EasyLoading.showToast('请上传身份证反面');
      return;
    }
    if (name == null) {
      EasyLoading.showToast('请输入名字');
      return;
    }
    if (cardNum == null) {
      EasyLoading.showToast('请输入身份证号');
      return;
    } else if (!ValidateTool.validateIDCard(cardNum!)) {
      EasyLoading.showToast('身份证号格式错误');
      return;
    }
    submitInfo(name!, cardNum!, topImgUrl!, bottomImgUrl!);
  }

  @override
  Widget build(BuildContext context) {
    double statusBarHeight = MediaQuery.of(context).padding.top;

    return Scaffold(
      resizeToAvoidBottomInset: true,
      backgroundColor: ClientColors.ff0a0f12,
      appBar: AppBar(
        iconTheme: IconThemeData(color: Colors.white),
        leading: IconButton(
          onPressed: () => {Get.back()},
          icon: Icon(Icons.arrow_back_ios),
        ),
        actions: [
          GestureDetector(
            onTap: () {
              _doneAction();
            },
            child: Container(
              margin: EdgeInsets.only(right: 10),
              child: Text(
                '完成',
                style: TextStyle(fontSize: 14, color: ClientColors.ff4abc9c),
              ),
            ),
          ),
        ],
        centerTitle: false,
        titleSpacing: FloatConstance.navBarSpace,
        backgroundColor: ClientColors.odffffff,
        title: Text(
          '实名认证',
          textAlign: TextAlign.left,
          style: TextStyle(color: Colors.white, fontSize: 18),
        ),
      ),
      body: Stack(
        children: [
          Image.asset(
            'assets/images/real_name_authentication_bg.png',
            fit: BoxFit.cover,
            height: double.infinity,
            width: double.infinity,
          ),
          SizedBox(
            width: double.infinity,
            child: SingleChildScrollView(
              child: Column(
                children: [
                  GestureDetector(
                    onTap: () => {_takePhoto(0)},
                    child: SizedBox(
                      width: 344,
                      height: 235,
                      child: Stack(
                        alignment: Alignment.bottomCenter,
                        children: [
                          Align(
                            alignment: Alignment.center,
                            child: Image.asset(
                              "assets/images/icon_real_vector.png",
                            ),
                          ),
                          _imageTop == null
                              ? Stack(
                                alignment: Alignment.center,
                                children: [
                                  Align(
                                    alignment: Alignment.center,
                                    child: Image.asset(
                                      "assets/images/icon_real_vector_middle.png",
                                    ),
                                  ),
                                  Align(
                                    alignment: Alignment.center,
                                    child: Image.asset(
                                      "assets/images/icon_real_vector_center.png",
                                    ),
                                  ),
                                ],
                              )
                              : SizedBox(
                                width: 300,
                                child: Image.file(_imageTop!, fit: BoxFit.fill),
                              ),

                          Text(
                            '身份证正面',
                            style: TextStyle(
                              color: ClientColors.f80FFFFFF,
                              fontSize: 12,
                              fontWeight: FontWeight.w400,
                            ),
                          ),
                        ],
                      ),
                    ).marginOnly(top: 23),
                  ),
                  GestureDetector(
                    onTap: () => {_takePhoto(1)},
                    child: SizedBox(
                      width: 344,
                      height: 235,
                      child: Stack(
                        alignment: Alignment.bottomCenter,
                        children: [
                          Align(
                            alignment: Alignment.center,
                            child: Image.asset(
                              "assets/images/icon_real_vector.png",
                            ),
                          ),

                          _image == null
                              ? Stack(
                                alignment: Alignment.center,
                                children: [
                                  Align(
                                    alignment: Alignment.center,
                                    child: Image.asset(
                                      "assets/images/icon_real_vector_middle_top.png",
                                    ),
                                  ),
                                  Align(
                                    alignment: Alignment.center,
                                    child: Image.asset(
                                      "assets/images/icon_real_vector_center.png",
                                    ),
                                  ),
                                ],
                              )
                              : SizedBox(
                                width: 300,
                                child: Image.file(_image!, fit: BoxFit.fill),
                              ),
                          Text(
                            '身份证反面',
                            style: TextStyle(
                              color: ClientColors.f80FFFFFF,
                              fontSize: 12,
                              fontWeight: FontWeight.w400,
                            ),
                          ),
                        ],
                      ),
                    ).marginOnly(top: 17),
                  ),

                  Container(
                    height: 60,
                    // color: ClientColors.odffffff,
                    decoration: BoxDecoration(
                      borderRadius: BorderRadius.circular(15),
                      color: ClientColors.odffffff,
                    ),

                    child: Row(
                      children: [
                        Text(
                          '姓名',
                          style: TextStyle(
                            color: ClientColors.f80FFFFFF,
                            fontSize: 15,
                            fontWeight: FontWeight.normal,
                          ),
                        ),
                        Spacer(),
                        SizedBox(
                          height: 50,
                          width: 250,
                          child: TextField(
                            textAlign: TextAlign.right,
                            style: TextStyle(color: Colors.white),
                            decoration: InputDecoration(
                              hintText: '用户名',
                              border: InputBorder.none,
                            ),
                            onChanged: (text) {
                              name = text;
                            },
                            onSubmitted: (text) {
                              log('提交内容: $text');
                            },
                          ),
                        ),
                      ],
                    ).paddingSymmetric(horizontal: 16),
                  ).marginOnly(top: 28, left: 16, right: 16),

                  Container(
                    height: 60,
                    decoration: BoxDecoration(
                      borderRadius: BorderRadius.circular(15),
                      color: ClientColors.odffffff,
                    ),

                    child: Row(
                      children: [
                        Text(
                          '身份证号',
                          style: TextStyle(
                            color: ClientColors.f80FFFFFF,
                            fontSize: 15,
                            fontWeight: FontWeight.normal,
                          ),
                        ),
                        Spacer(),
                        SizedBox(
                          height: 50,
                          width: 250,
                          child: TextField(
                            textAlign: TextAlign.right,
                            style: TextStyle(color: Colors.white),
                            decoration: InputDecoration(
                              hintText: '身份证号',
                              border: InputBorder.none,
                            ),
                            onChanged: (text) {
                              cardNum = text;
                            },
                            onSubmitted: (text) {
                              log('提交内容: $text');
                            },
                          ),
                        ),
                      ],
                    ).paddingSymmetric(horizontal: 16),
                  ).marginOnly(top: 15, left: 16, right: 16),
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }
}
